package com.linghu.web;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.linghu.pojo.ApiResponse;

import com.linghu.pojo.DouyinRequest;
import com.linghu.service.EventService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;



@RestController
@RequestMapping("/v2/order")
@Slf4j
public class SystemCallback {
    private final EventService eventService;
    private final ObjectMapper objectMapper;

    public SystemCallback(EventService eventService, ObjectMapper objectMapper) {
        this.eventService = eventService;
        this.objectMapper = objectMapper;
    }

    /**
     * 预订结果回调
     * @param request
     * @return
     */
    @PostMapping(value = "/bookingResultSys",consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> handleWebhook(@RequestBody DouyinRequest request) {
        String event = request.getEvent();
        JsonNode content = request.getContent();
        if ("verify_webhook".equals(event)) {
            try {
                if (content.has("challenge")) {
                    JsonNode challengeNode = content.get("challenge");
                    ObjectNode responseNode = objectMapper.createObjectNode();
                    responseNode.set("challenge", challengeNode);
                    String responseJson = objectMapper.writeValueAsString(responseNode);
                    return ResponseEntity.ok(responseJson);
                } else {
                    return ResponseEntity.badRequest().body("{\"error\": \"Missing challenge parameter\"}");
                }
            } catch (Exception e) {
                return ResponseEntity.badRequest().body("{\"error\": \"Invalid content format\"}");
            }
        } else {
            eventService.handleEvent(event, content);
            return ResponseEntity.ok("{\"status\": \"success\"}");
        }
    }

    @PostMapping("/startBooking")
    public ApiResponse startBooking(@RequestParam Map<String,String> params) {
        System.out.println(params);
        log.info("测试-params:{}",params);
        log.info("测试-msgType:{}",params.get("msgType"));
        return new ApiResponse(200, "ok");
    }
    @GetMapping("/hi")
    public void sayHi() {
        System.out.println("hello,world!");
        return ;
    }

}
